package com.yss.netty.handler;

import com.yss.netty.future.ResponseCallback;
import com.yss.netty.future.ResponseFuture;
import com.yss.netty.protocol.CommandType;
import com.yss.netty.protocol.Message;
import com.yss.netty.protocol.Ping;
import com.yss.netty.util.Host;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
@ChannelHandler.Sharable
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message message = (Message) msg;
        Channel channel = ctx.channel();
        InetSocketAddress socketAddress = (InetSocketAddress) channel.remoteAddress();

        log.info("\nReceive Message : {} from : {}", new String(message.getBody()), Host.of(socketAddress).getAddress());

        if (message.getCommandType() == CommandType.PONG) {
        } else {
            processReceivedMessage(message);
        }

    }

    /**
     * Handle message from other server
     *
     * @param message
     */
    private void processReceivedMessage(final Message message) {
        long opaque = message.getOpaque();
        ResponseFuture responseFuture = ResponseFuture.getResponseFuture(opaque);
        ResponseCallback callback = responseFuture.getCallback();
        if (callback != null) {
            // async
            responseFuture.executeCallback(message);
        } else {
            // sync
            responseFuture.putResponse(message);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("\nNettyServerHandler has an exception : {} ", cause.getMessage());
        ctx.channel().close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            ByteBuf ping = Ping.ping();
            ctx.channel().writeAndFlush(ping);
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
